#!/usr/bin/env python

from glob import iglob
import optparse
from os.path import basename
from os.path import join as pathjoin
import re
import sys

from charmicat import BadCommandLineError

def main():
    '''
    Usage: csbbelle_files_left.py [opts] all_files.ls processed_files/
    
    Scan `processed_files' for files with exp and run numbers that match those
    in `all_files.ls', and print out the lines from `all_files.ls' that have
    no match.
    '''

    op = optparse.OptionParser(usage=main.__doc__)
    op.add_option("-o", "--output", dest='output', default=None,
                  help="Leave output in `FILE.ls'", metavar='FILE.ls')

    opts, args = op.parse_args()

    if len(args) < 2:
        msg = "Please supply a list file and a directory path"
        raise BadCommandLineError(msg, -1)

    rx = r'(e0000[0-9][0-9]r[0-9]{6})'

    with open(args[0]) as fpall:
        all_files = {}
        for l in fpall:
            try:
                k = re.search(rx, l).groups()[0]
            except AttributeError:
                if opts.verbose:
                    msg = "`{0}' does not match Belle run/exp pattern\n"
                    sys.stderr.write(msg.format(l.strip()))
                    sys.stderr.flush()

            all_files[k] = l.strip()
    
    processed_files = {}
    for path in iglob(pathjoin(args[1], '*')):
        try:
            k = re.search(rx, path).groups()[0]
        except AttributeError:
            if opts.verbose:
                msg = "`{0}' does not match Belle run/exp pattern\n"
                sys.stderr.write(msg.format(path.strip()))
                sys.stderr.flush()
        
        processed_files[k] = path
        
    files_left = sorted(set(all_files.keys()) - set(processed_files.keys()))
    
    if opts.output is None:
        opts.output = sys.stdout
    else:
        opts.output = open(opts.output, 'w')

    opts.output.write('\n'.join([all_files[k] for k in files_left]) + '\n')
        
    return 0


if __name__ == '__main__':
    try:
        import sys
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
            
